package cn.edu.bzu.aaa.servlet.loginregistservlet;

import cn.edu.bzu.aaa.model.User;
import cn.edu.bzu.aaa.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/login1")
public class loginservlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService service = new UserService();
        System.out.println(username + password);
        int a = service.validateUser(username, password);
        System.out.println(a);
        if (!service.IsRegistrationComplete(username)) {
            resp.sendRedirect("/registtt.html");
        }
        else if (service.isUserLocked(username)) {
            // 用户被锁定
            request.getRequestDispatcher("/lockname.jsp").forward(request, resp);
        } else if (a == 0) {
            // 情况2：没有username
            request.getRequestDispatcher("/loginname.jsp").forward(request, resp);
        } else if (a == 1) {
            // 情况1：有username但是密码错误
            HttpSession session1 = request.getSession();
            int b=3;
            session1.setAttribute("count", b);
            request.getRequestDispatcher("/login.jsp").forward(request, resp);
        } else if (a == 2) {
            // 情况3：账号密码全部正确
            HttpSession session2 = request.getSession();
            session2.setAttribute("username", username);
            //java获取当前时间
            Date currentDate = new Date();
            service.updateLastLoginDate(username, currentDate); // 更新最后登录时间
            resp.getWriter().println("登录成功");
            // 可以在这里添加其他逻辑，例如重定向到用户主页
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
